package com.yun.util;


import com.yun.pojo.User;
import com.yun.service.DirectorService;
import com.yun.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


/*自定义UserRealm*/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    DirectorService directorService;

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        /*SimpleAuthorizationInfo 简单的授权信息*/
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //自己定义的权限，不是从数据库获取的info.addStringPermission("user:add");
        /*从数据库获取权限信息*/
        //1.获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        //2.从认证里面拿出当前用户信息
        User login = (User) subject.getPrincipal();
        //3.设置当前用户权限
        info.addStringPermission(login.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //数据库的真实用户
        User user = userService.queryByUserName(userToken.getUsername());//用户
        if (user!=null){
            return new SimpleAuthenticationInfo(user,user.getPwd(),"");
        }
        return null;
    }
}
